import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
//配置vuex持久化操作
import VuexPersist from "vuex-persist";

//实例化对象
const VuexLocal = new VuexPersist({
  storage: window.sessionStorage
})

export default new Vuex.Store({
  state: {
    users: {},
    cartList: [],
    history:['Vue3.0和2.0的区别','前端到底都得会啥'],
  },
  mutations: {
    //添加历史记录
    addHistory(state,item){
      //判断历史记录条数
      if(state.history.length>=8){
        state.history.pop();
      }

      state.history.unshift(item);//追加到最前面去。
    },
    //清空历史记录
    clearHistory(state){
      state.history = [];
    },
    //登陆操作
    login(state, data) {
      console.log('调用vuex中的数据');
      state.users = data;
    },
    //vuex退出登陆
    logout(state) {
      state.users = {};
    },
    //加入购物车的逻辑
    addCart(state, goods) {
      //通过findIndex方法，判断传递过来的——id值是否存在,如果存在大于-1
      let index = state.cartList.findIndex(item => {
        return item._id == goods._id;
      })
      //大于-1说明商品已经添加过了
      if (index > -1) {
        state.cartList[index].num++;
      } else {//商品并未添加过
        state.cartList.unshift(goods);
      }

    },
    //购物车数据的全选全不选的逻辑
    checkAll(state, checked) {
      console.log("全选方法", checked);
      //遍历数组的值，map方法
      state.cartList.map(item => {
        item.checked = checked;
      })
    }
  },
  actions: {

  },
  getters: {
    //计算总价格
    totals(state) {
      let amounts = 0;

      state.cartList.forEach(item=>{
        if(item.checked == true){
          amounts += item.price*item.num;
        }
      })

      return amounts;
      //循环遍历vuex中state中的值
      return state.cartList.reduce((prev, cur) => {
        if (cur.checked == true) {
          prev += cur.num *cur.price;
        }
        return prev;
      },0);
    }
  },
  modules: {

  },
  plugins: [VuexLocal.plugin],
})
